package com.ikun.aimian.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.aimian.common.ErrorCode;
import com.ikun.aimian.exception.ThrowUtils;
import com.ikun.aimian.mapper.FeedbackMapper;
import com.ikun.aimian.model.dto.feedback.FeedbackQueryRequest;
import com.ikun.aimian.model.entity.Feedback;
import com.ikun.aimian.model.entity.App;
import com.ikun.aimian.model.entity.User;
import com.ikun.aimian.model.vo.FeedbackVO;
import com.ikun.aimian.service.FeedbackService;
import com.ikun.aimian.service.AppService;
import com.ikun.aimian.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Resource
    private UserService userService;

    @Resource
    private AppService appService;

    @Override
    public void validFeedback(Feedback feedback, boolean add) {
        ThrowUtils.throwIf(feedback == null, ErrorCode.PARAMS_ERROR);
        String content = feedback.getContent();
        Long appId = feedback.getAppId();
        // 新增时必须传入内容和 appId
        if (add) {
            ThrowUtils.throwIf(StringUtils.isBlank(content), ErrorCode.PARAMS_ERROR, "反馈内容不能为空");
            ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR, "appId 非法");
        }
        // 可选：反馈内容长度限制
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.length() > 1000, ErrorCode.PARAMS_ERROR, "反馈内容过长");
        }
        // 验证 appId 是否存在
        if (appId != null) {
            App app = appService.getById(appId);
            ThrowUtils.throwIf(app == null, ErrorCode.PARAMS_ERROR, "应用不存在");
        }
    }

    @Override
    public QueryWrapper<Feedback> getQueryWrapper(FeedbackQueryRequest queryRequest) {
        QueryWrapper<Feedback> queryWrapper = new QueryWrapper<>();
        if (queryRequest == null) {
            return queryWrapper;
        }
        // 按 appId 精确匹配
        if (queryRequest.getAppId() != null) {
            queryWrapper.eq("appId", queryRequest.getAppId());
        }
        // 按 userId 精确匹配
        if (queryRequest.getUserId() != null) {
            queryWrapper.eq("userId", queryRequest.getUserId());
        }
        // 时间范围筛选（可选）
        if (queryRequest.getStartTime() != null && queryRequest.getEndTime() != null) {
            queryWrapper.between("createTime", queryRequest.getStartTime(), queryRequest.getEndTime());
        }
        // 排序
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder(); // "ascend" 或 "descend"
        if (StringUtils.isNotBlank(sortField)) {
            if ("ascend".equalsIgnoreCase(sortOrder)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByDesc(sortField);
            }
        } else {
            queryWrapper.orderByDesc("createTime");
        }
        return queryWrapper;
    }

    @Override
    public FeedbackVO getFeedbackVO(Feedback feedback, HttpServletRequest request) {
        if (feedback == null) {
            return null;
        }
        // 基本字段转换
        FeedbackVO feedbackVO = FeedbackVO.fromEntity(feedback);

        // 查询用户信息，补充 userName（头像等可选）
        Long userId = feedback.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            if (user != null) {
                feedbackVO.setUserName(user.getUserName());
            }
        }

        // 查询应用信息，补充 appName
        Long appId = feedback.getAppId();
        if (appId != null && appId > 0) {
            App app = appService.getById(appId);
            if (app != null) {
                feedbackVO.setAppName(app.getAppName());
            }
        }

        return feedbackVO;
    }

    @Override
    public Page<FeedbackVO> getFeedbackVOPage(Page<Feedback> feedbackPage, HttpServletRequest request) {
        List<Feedback> feedbackList = feedbackPage.getRecords();
        Page<FeedbackVO> feedbackVOPage = new Page<>(feedbackPage.getCurrent(), feedbackPage.getSize(), feedbackPage.getTotal());
        if (CollUtil.isEmpty(feedbackList)) {
            return feedbackVOPage;
        }
        List<FeedbackVO> feedbackVOList = feedbackList.stream()
                .map(feedback -> getFeedbackVO(feedback, request))
                .collect(Collectors.toList());
        feedbackVOPage.setRecords(feedbackVOList);
        return feedbackVOPage;
    }
}
